package com.ms.p2p.controller.wap;


import com.ms.common.bean.Message;
import com.ms.common.exception.NoticeException;
import com.ms.common.exception.ResourceNotFoundException;
import com.ms.common.utils.AppContext;
import com.ms.common.utils.CacheUtils;
import com.ms.common.utils.MsDateUtils;
import com.ms.common.utils.WebErrors;
import com.ms.p2p.Constants;
import com.ms.p2p.entity.member.Member;
import com.ms.p2p.entity.system.AdminUser;
import com.ms.p2p.template.directive.FlashMessageDirective;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.PropertyEditorSupport;
import java.io.IOException;
import java.text.ParseException;
import java.util.Date;

import static com.ms.common.utils.WebErrors.ERROR_ATTR_NAME;

public class WapBaseController {

    protected static Logger logger = Logger.getLogger(WapBaseController.class);

    protected static final String FRONT_ERROR_PAGE = "/wap/common/error";

    protected static final Message successMessage = Message.success("操作成功");
    protected static final Message errorMMessage = Message.error("操作失败");


    //private static CacheManager cacheManager = SpringContextHolder.getBean(CacheManager.class);


    public Member getCurrentUser() {
        return  (Member) AppContext.getSessionAttr(Constants.PRINCIPAL_SESSION_NAME);
    }

    public AdminUser getCurrentEmp() {
        return (AdminUser) AppContext.getSessionAttr(Constants.PRINCIPAL_ADMIN_NAME);
    }

    protected void addActionError(HttpServletRequest request, String message) {
        WebErrors errors = (WebErrors) request.getAttribute(ERROR_ATTR_NAME);
        if (errors == null) {
            errors = WebErrors.create();
            request.setAttribute(ERROR_ATTR_NAME, errors);
        }
        errors.addErrorString(message);
    }
    protected void addFlashMessage(RedirectAttributes redirectAttributes, Message message) {
        if (redirectAttributes != null && message != null) {
            redirectAttributes.addFlashAttribute(FlashMessageDirective.FLASH_MESSAGE_ATTRIBUTE_NAME, message);
        }
    }
    //private static CacheManager cacheManager = SpringContextHolder.getBean(CacheManager.class);
//    protected  void clearCache(){
//        for (String cacheName:cacheManager.getCacheNames()){
//            cacheManager.getCache(cacheName).clear();
//
//        }
//    }


    protected  void clearToken(){
        AppContext.removeAttribute(Constants.VALIDATE_TOKEN_KEY);
    }

    @InitBinder
    protected void initBinder(WebDataBinder binder) {

            // String类型转换，将所有传递进来的String进行HTML编码，防止XSS攻击
            binder.registerCustomEditor(String.class,
                    new PropertyEditorSupport() {
                        @Override
                        public void setAsText(String text) {
                            setValue(text == null ? null : StringEscapeUtils
                                    .escapeHtml4(text.trim()));
                        }

                        @Override
                        public String getAsText() {
                            Object value = getValue();
                            return value != null ? value.toString() : "";
                        }
                    });
            // Date 类型转换
            binder.registerCustomEditor(Date.class,
                    new PropertyEditorSupport() {
                        @Override
                        public void setAsText(String text) {
                            try {
                                setValue(MsDateUtils.parseDate(text, "yyyy-MM-dd HH:mm:ss"));
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                        }

                    });

    }

    @ExceptionHandler
    public void exceptionHandler(Exception ex, HttpServletResponse response,
                                 HttpServletRequest request) throws IOException, ServletException {
        if (AppContext.isAjax(request)) {

            if (ex.getClass() == NoticeException.class) {
                this.addActionError(request, ex.getMessage());
            } else {
                ex.printStackTrace();
                logger.error("系统错误", ex);
                this.addActionError(request, "系统错误!");
            }
            WebErrors errors = (WebErrors) request
                    .getAttribute(ERROR_ATTR_NAME);
            errors.showErrorAjax(response);
        } else {
            if (ex.getClass() == NoticeException.class) {
                this.addActionError(request, ex.getMessage());
                request.getRequestDispatcher(FRONT_ERROR_PAGE).forward(request,
                        response);
            } else if (ex.getClass() == ResourceNotFoundException.class) {
                response.sendRedirect("/wap/common/resource_not_found");
            } else {
                ex.printStackTrace();
                logger.error("系统错误", ex);
                this.addActionError(request, "系统错误");
                request.getRequestDispatcher(FRONT_ERROR_PAGE).forward(request,
                        response);
            }
        }
    }


    protected String isValidSms(String mobile, String captcha, boolean isValidCaptcha){

        //是否验证图形验证码
        if(isValidCaptcha) {
            //验证码校验
            String code = (String) AppContext.getSessionAttr(Constants.CAPTCHA_SESSION_KEY);
            if (StringUtils.isBlank(code) || StringUtils.isBlank(captcha) || !code.toLowerCase().equals(captcha.toLowerCase())) {
                return "图形验证错误或已过期失效";
            }
        }

        //频繁发送限制
        String cacheKey = "mobile_code_" + mobile;
        Object ct = CacheUtils.getCacheValue("mobileCode", cacheKey);
        if (ct != null && Integer.valueOf(String.valueOf(ct)) >= 10) {
            logger.info(mobile+",发送过于频繁，请您稍后再试！ct="+ct);
            return "发送过于频繁，请您稍后再试！";
        }

        //
        if (ct == null) {
            CacheUtils.setCacheValue("mobileCode", cacheKey, 1);
        } else {
            CacheUtils.setCacheValue("mobileCode", cacheKey, Integer.valueOf(String.valueOf(ct)) + 1);
        }

        return "";
    }
}
